from django.contrib import admin

from .models import Tag, Category, Post


class DateFormatMixin:
    """混合类，格式化日期时间，人性化"""
    def format_created(self, post_obj):
        return post_obj.created.strftime('%Y年%m月%d日 %H:%M')

    format_created.short_description = '创建时间'


@admin.register(Post)
class PostAdmin(DateFormatMixin, admin.ModelAdmin):
    # 注意输入中文时不会自动填充，如果文章标题中出现中英文混合时会造成只保存英文，
    # 因此避免使用
    # prepopulated_fields = {'slug': ('title',)}
    # list_display = ('title', 'slug', 'img', 'status', 'format_created', 'category', 'display_tags')
    list_display = ('title', 'img', 'status', 'format_created', 'category', 'display_tags')
    # exclude = ('slug',)
    list_editable = ('status',)  # 可编辑字段必须出现在list_display中
    list_per_page = 25

    def display_tags(self, post_obj):
        return ', '.join(tag.name for tag in post_obj.tags.all())

    display_tags.short_description = '标签'


@admin.register(Tag)
class TagAdmin(DateFormatMixin, admin.ModelAdmin):
    list_display = ('name', 'format_created')


@admin.register(Category)
class CategoryAdmin(DateFormatMixin, admin.ModelAdmin):
    list_display = ('name', 'format_created')
